package com.hb.game.pk.utils;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;

public class SocketUtils {

    private WebSocketClient client;
    private String url;
    private String text;
    private OnErrorListener errorListener;
    private OnCloseListener closeListener;
    private OnMessageListener messageListener;
    private OnOpenListener openListener;

    public SocketUtils(String url, String text) {
        this.url = url;
        this.text = text;
    }

    public WebSocketClient open() throws URISyntaxException {
        if (client == null) {
            client = new WebSocketClient(new URI(url)) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    LogUtils.d("onOpen");
                    openListener.setOnOpenListener(handshakedata);
                }

                @Override
                public void onMessage(String message) {
                    LogUtils.d("onMessage");
                    messageListener.setOnMessageListener(message);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    LogUtils.d("onClose");
                    closeListener.setOnCloseListener(code, reason, remote);
                }

                @Override
                public void onError(Exception ex) {
                    LogUtils.d("onError");
                    errorListener.setOnErrorListener(ex);
                }
            };
        }
//        client.setConnectionLostTimeout(5);
        return client;
    }

    public interface OnOpenListener {
        void setOnOpenListener(ServerHandshake handshakedata);
    }

    public interface OnMessageListener {
        void setOnMessageListener(String message);
    }

    public interface OnCloseListener {
        void setOnCloseListener(int code, String reason, boolean remote);
    }

    public interface OnErrorListener {
        void setOnErrorListener(Exception ex);
    }

    public void setOnOpenListener(OnOpenListener openListener) {
        this.openListener = openListener;
    }

    public void setOnMessageListener(OnMessageListener messageListener) {
        this.messageListener = messageListener;
    }

    public void setOnCloseListener(OnCloseListener closeListener) {
        this.closeListener = closeListener;
    }

    public void setOnErrorListener(OnErrorListener errorListener) {
        this.errorListener = errorListener;
    }

    public void setText(String str) {
        client.send(str);
    }
}
